package com.youthburin.base.spring;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

public class SessionValidatorFilter extends OncePerRequestFilter {
	private final String loginUrl = "/login";

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		HttpSession session = request.getSession(false);

		if (!request.getRequestURI().contains(loginUrl)) {
			if (session == null) {
				if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))
						|| request.getParameter("ajax") != null) {
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(
							"{'statusCode':'301', 'message':'"
									+ getMessage("error.common.sessiontimeout", request.getSession())
									+ "',callbackType:'closeCurrent'}");
					response.getWriter().close();
				} else {
					response.sendRedirect(request.getContextPath() + this.loginUrl);
				}
			} else {
				filterChain.doFilter(request, response);
			}
		} else {
			filterChain.doFilter(request, response);
		}
	}

	private String getMessage(String code, HttpSession session) {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
		return context.getMessage(code, null, code,
				(Locale) session.getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME));
	}
}
